//
//  LocationService.swift
//  CitySearch
//
//  Created by guotonglin on 2020/6/5.
//  Copyright © 2020 guotonglin. All rights reserved.
//

import Foundation
import CoreLocation
import RxSwift
import RxCocoa

class LocationService: NSObject {
    
    static let shared: LocationService = LocationService()
    private let manager = CLLocationManager()
    
    private let currentLocaitonRelay: BehaviorRelay<(lat: Double, lon: Double)?> = BehaviorRelay(value: nil)
    
    lazy var currentLocation: Observable<(lat: Double, lon: Double)?> = self.currentLocaitonRelay.asObservable().share(replay: 1, scope: .forever)
    
    private override init() {
        super.init()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        manager.requestWhenInUseAuthorization()
        
        if CLLocationManager.locationServicesEnabled() {
            manager.startUpdatingLocation()
        }
    }
    deinit {
        self.manager.stopUpdatingLocation()
    }
}

extension LocationService: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            let currentLocation = (
                lat: location.coordinate.latitude,
                lon: location.coordinate.longitude
            )
            self.currentLocaitonRelay.accept(currentLocation)
            self.manager.stopUpdatingLocation()
        }
    }
}
